package com.idanchuang.component.mq.amqp;

import com.alibaba.mq.amqp.utils.UserUtils;
import com.idanchuang.component.mq.amqp.config.ComponentAmqpConfig;
import com.rabbitmq.client.impl.CredentialsProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class AliyunCredentialsProvider implements CredentialsProvider {

    /**
     * Access Key ID.
     */
    private final String accessKeyId;
    /**
     * Access Key Secret.
     */
    private final String accessKeySecret;
    /**
     * security temp token. (optional)
     */
    private final String securityToken;
    /**
     * instanceId
     */
    private final String instanceId;


    public AliyunCredentialsProvider(final RabbitProperties rabbitProperties, final ComponentAmqpConfig amqpConfig) {
        this(rabbitProperties.getUsername(),
                rabbitProperties.getPassword(),
                amqpConfig.getSecurityToken(),
                amqpConfig.getInstanceId());
    }

    public AliyunCredentialsProvider(String username, String password, String securityToken, String instanceId) {
        if (instanceId == null) {
            throw new IllegalArgumentException("Lack configs, you should add config: [spring.rabbitmq.amqp.instanceId]");
        }
        this.accessKeyId = username;
        this.accessKeySecret = password;
        this.securityToken = securityToken;
        this.instanceId = instanceId;
    }

    @Override
    public String getUsername() {
        if(StringUtils.isNotEmpty(securityToken)) {
            return UserUtils.getUserName(accessKeyId, instanceId, securityToken);
        } else {
            return UserUtils.getUserName(accessKeyId, instanceId);
        }
    }

    @Override
    public String getPassword() {
        try {
            return UserUtils.getPassord(accessKeySecret);
        } catch (InvalidKeyException | NoSuchAlgorithmException e) {
            //todo
        }
        return null;
    }
}
